package com.example.open.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.base.security.SysUser;
import com.example.base.security.SysUserType;
import com.example.base.system.domain.OpenUserToken;
import com.example.base.system.domain.SysUserOpen;
import com.example.base.system.service.OpenUserTokenService;
import com.example.base.system.service.SysConfigService;
import com.example.base.system.service.SysUserOpenService;
import com.example.base.utils.DateUtils;
import com.example.base.utils.Md5Utils;
import com.example.base.utils.Result;
import com.example.base.utils.TextEncryptUtils;
import com.example.base.validation.utils.ValidatedUtils;
import com.example.open.service.OpenUserLoginService;
import com.example.open.vo.OpenUserRegisterVo;
import com.example.open.vo.OpenUserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
public class OpenUserLoginServiceImpl implements OpenUserLoginService {

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private SysUserOpenService sysUserOpenService;

    @Autowired
    private OpenUserTokenService openUserTokenService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public JSONObject login(String userName, String passWord) {
        return null;
    }

    @Override
    public JSONObject login(String code) {
        return null;
    }

    @Override
    public JSONObject login(OpenUserVo vo) {
        SysUserOpen userOpen=null;
        boolean isMail=ValidatedUtils.isMail(vo.getUserName());
        if(isMail){
            userOpen=sysUserOpenService.getSysUserOpenByMail(vo.getUserName());
        }else if(ValidatedUtils.isMobile(vo.getUserName())){
            userOpen=sysUserOpenService.getSysUserOpenByPhone(vo.getUserName());
        }else {
            userOpen=sysUserOpenService.getSysUserOpenByUserName(vo.getUserName());
        }
        if(userOpen==null){
            return Result.errorInfo("账号或密码错误");
        }
        boolean isTrue=bCryptPasswordEncoder.matches(vo.getPassWord(),userOpen.getPassword());
        if(!isTrue){
            return Result.errorInfo("账号或密码错误");
        }
        String token=this.createToken(userOpen);
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("token",token);
        return Result.successInfo("登录成功",jsonObject);
    }

    @Override
    public String createToken(SysUserOpen sysUserOpen) {
        String token=UUID.randomUUID().toString().replaceAll("-","")+"-"+UUID.randomUUID().toString().replaceAll("-","")+"-"+UUID.randomUUID().toString().replaceAll("-","");
        OpenUserToken openUserToken=new OpenUserToken();
        openUserToken.setCreatedate(new Date());
        Date expireDate=DateUtils.getDate30MinuteAfter();
        openUserToken.setExpiredate(expireDate);
        openUserToken.setUserid(sysUserOpen.getUuid());
        openUserToken.setToken(token);
        openUserToken.setUsername(sysUserOpen.getUsername());
        openUserTokenService.save(openUserToken);
        return token;
    }

    @Override
    public JSONObject register(OpenUserRegisterVo vo) {
        SysUserOpen sysUserOpen=valitedOpenUserExisted(vo);
        if(!vo.getAgainPassWord().equals(vo.getPassword())){
            return Result.errorInfo("两次密码不一致");
        }
        if(sysUserOpen!=null){
            if(vo.getMobile().equals(sysUserOpen.getMobile())){
                return Result.errorInfo(sysUserOpen.getMobile()+"手机号已存在");
            }
            if(vo.getEMail().equals(sysUserOpen.getEMail())){
                return Result.errorInfo(sysUserOpen.getEMail()+"邮箱账号已存在");
            }
            if(vo.getUsername().equals(sysUserOpen.getUsername())){
                return Result.errorInfo(sysUserOpen.getUsername()+"账号已存在");
            }
            return Result.errorInfo("系统错误,请刷新后重试");
        }
        sysUserOpen=new SysUserOpen();
        BeanUtils.copyProperties(vo,sysUserOpen);
        String password=bCryptPasswordEncoder.encode(Md5Utils.encrypt(vo.getPassword()));
        sysUserOpen.setPassword(password);
        sysUserOpen.setDeleted(0);
        sysUserOpen.setCreatetime(new Date());
        sysUserOpen.setUpdatetime(new Date());
        sysUserOpen.setLoginFailNum(0);
        sysUserOpen.setLoginFailTotalnum(0);
        sysUserOpen.setOpenType(SysUserType.OPEN.getUserType());
        sysUserOpenService.save(sysUserOpen);
        return Result.successInfo("注册成功");
    }

    @Override
    public JSONObject appOpenUserLogin(String userName, String appName) {
        if(appName.equals("system")){
            return Result.errorInfo("开放类型不得为system");
        }
        LambdaQueryWrapper<SysUserOpen> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUserOpen::getUsername,userName);
        SysUserOpen userOpen=sysUserOpenService.getOne(lambdaQueryWrapper);
        if(userOpen==null){
            userOpen=new SysUserOpen();
            userOpen.setUsername(userName);
            String password=bCryptPasswordEncoder.encode(Md5Utils.encrypt(sysConfigService.getInitPassWord()));
            userOpen.setPassword(password);
            userOpen.setOpenType(appName);
            userOpen.setCreatetime(new Date());
            userOpen.setDeleted(0);
            userOpen.setLoginFailTotalnum(0);
            userOpen.setLoginFailNum(0);
            userOpen.setUpdatetime(new Date());
            sysUserOpenService.save(userOpen);
        }
        if(!userOpen.getOpenType().equals("system")){
            String token=createToken(userOpen);
            JSONObject json=new JSONObject();
            json.put("token",token);
            json.put("username",userName);
            return Result.successInfo(json);
        }
        return Result.errorInfo("登录失败");
    }

    @Override
    public SysUserOpen valitedOpenUserExisted(OpenUserRegisterVo vo) {
        LambdaQueryWrapper<SysUserOpen> user=new LambdaQueryWrapper<>();
        user.eq(SysUserOpen::getEMail,vo.getEMail());
        user.or().eq(SysUserOpen::getMobile,vo.getMobile());
        user.or().eq(SysUserOpen::getUsername,vo.getUsername());
        SysUserOpen userOpen=sysUserOpenService.getOne(user);
        return userOpen;
    }


}
